package com.jiufen.Interceptor;

import com.jiufen.Utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 令牌校验的拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {


    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 在目标资源方法生效前 生效 做拦截器使用
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("拦截器开始拦截！");

        //1.获取请求路径
        String requestURI = request.getRequestURI();
        log.debug("请求路径为:{}",requestURI);

        //2.判断是否是登录请求 准备过滤 如是登录请求 放行 return true  即可放行
        if (requestURI.contains("login") || requestURI.contains("register")) {
            log.info("本次请求不需要处理");
            return true;
        }

        //3.获取请求头token
        String token = request.getHeader("token");
        log.debug("本次请求的token是=={}", token);

        //4.判断token是否为空  如果为空 返回响应401 不为空 解析token
        if (token == null) {
            log.info("请求头为空，返回登录页面");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //5.解析token 失败 返回401
        try {
            //解析token
            Map<String, Object> stringObjectMap = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            log.info("token解析失败");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6.成功 放行请求
        log.info("令牌合法 开始放行~");
        return true;

    }
}
